<script lang="ts" setup>
import {nextTick, onMounted, reactive, ref} from "vue";
import {reqAddOrUpdateTrademark, reqDeleteTrademark, reqHasTrademark} from "../../../api/product/trademark"
import type {TradeMark} from "../../../api/product/trademark/type.ts";
import {ElMessage, type UploadProps} from "element-plus";

let limit = ref(3);
let pageNo = ref(1);
let total = ref(0);
let trademarkArr = ref();
const formRef = ref();

const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager;
  let result = await reqHasTrademark(pageNo.value, limit.value);
  console.log(result);
  if (result.code == 200) {
    total.value = result.data.total;
    trademarkArr.value = result.data.records;
  }
}

onMounted(() => {
  getHasTrademark();
});

let dialogVisible = ref();

let trademarkParams = reactive<TradeMark>({
  tmName: "",
  logoUrl: "",
});

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
      rawFile.type === "image/png" ||
      rawFile.type === "image/jpeg" ||
      rawFile.type === "image/gif" ||
      rawFile.type === "image/webp"
  ) {
    if (rawFile.size / 1024 / 1024 < 10) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传文件不能小于4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "文件格式得是PNG,JPEG,GIF"
    });
    return false;
  }
}

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  trademarkParams.logoUrl = response.data;
  formRef.value.clearValidate("logoUrl");
}

const openTrademark = () => {
  dialogVisible.value = true;
  trademarkParams.id = 0;
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";

  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });
}

const cancel = () => {
  dialogVisible.value = false;
}

const confirm = async () => {
  await formRef.value.validate();
  const result = await reqAddOrUpdateTrademark(trademarkParams);
  if (result.code == 200) {
    dialogVisible.value = false;
    ElMessage({
      type: "success",
      message: trademarkParams.id ? '修改成功' : '添加成功'
    });
    await getHasTrademark(trademarkParams.id ? pageNo.value : 1);
  } else {
    dialogVisible.value = false;
    ElMessage({
      type: "error",
      message: trademarkParams.id ? '修改失败' : '添加失败'
    })
  }
}

const updateTrademark = (row: any) => {
  dialogVisible.value = true;
  Object.assign(trademarkParams, row);

  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });
}

//@ts-ignore
const validatorTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length > 1) {
    callback();
  } else {
    callback(new Error("长度不可小于2"));
  }
}

//@ts-ignore
const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  if (value) {
    callback();
  } else {
    callback(new Error("文件必须上传"));
  }
}

const rules = reactive({
  tmName: [{require: true, validator: validatorTmName, trigger: 'blur'}],
  logoUrl: [{require: true, validator: validatorLogoUrl}],
});

const removeTrademark = async (id: number) => {
  const result = await reqDeleteTrademark(id);
  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: "删除信息成功"
    });
    await getHasTrademark(trademarkArr.value.length > 1 ? pageNo.value : --pageNo.value);
  } else {
    ElMessage({
      type: "error",
      message: "删除信息失败"
    });
  }
}

</script>

<template>
  <el-card class="box-card">
    <el-button icon="Plus" type="primary" @click="openTrademark">添加品牌</el-button>

    <el-table :data="trademarkArr" border style="margin: 10px 0">
      <el-table-column
          align="center"
          label="序号"
          type="index"
          width="80px"
      ></el-table-column>
      <el-table-column label="品牌名称">
        <template #default="{row, $index}">
          <pre>{{ row.tmName }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="品牌LOGO">
        <template #default="{row, $index}">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px;">
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template v-slot:default="{row}">
          <el-button icon="Edit" type="primary" @click="updateTrademark(row)"></el-button>
          <el-popconfirm :title="`确定删除${row.tmName}`" icon="Delete" @confirm="removeTrademark(row.id)">
            <template #reference>
              <el-button icon="Delete" type="danger"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :pager-count="7"
        :total="total"
        background
        layout="prev, pager, next, jumper,->,total, sizes,"
        @current-change="getHasTrademark(pageNo)"
        @size-change="getHasTrademark(1)"/>
  </el-card>

  <el-dialog
      v-model="dialogVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
      width="500"
  >
    <el-form ref="formRef" :model="trademarkParams" :rules="rules" style="width: 80%">
      <el-form-item label="品牌名称" label-width="80px" prop="tmName">
        <el-input v-model="trademarkParams.tmName" placeholder="输入品牌名称"/>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
        <el-upload
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            action="/api/admin/product/fileUpload"
            class="avatar-uploader"
        >
          <img v-if="trademarkParams.logoUrl"
               :src="trademarkParams.logoUrl"
               alt=""
               class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.box-card {
  width: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
}
</style>